package com.jeffmony.sample;

import android.app.Activity;
import android.content.Context;
import android.graphics.SurfaceTexture;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.google.android.exoplayer2.DefaultLoadControl;
import com.google.android.exoplayer2.ExoPlaybackException;
import com.google.android.exoplayer2.ExoPlayerFactory;
import com.google.android.exoplayer2.LoadControl;
import com.google.android.exoplayer2.PlaybackParameters;
import com.google.android.exoplayer2.Player;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.source.hls.HlsMediaSource;
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector;
import com.google.android.exoplayer2.trackselection.TrackSelector;
import com.google.android.exoplayer2.ui.PlayerView;
import com.google.android.exoplayer2.upstream.DataSource;
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory;
import com.google.android.exoplayer2.upstream.DefaultHttpDataSourceFactory;
import com.google.android.exoplayer2.util.Util;
import com.jeffmony.playersdk.IPlayer;
import com.jeffmony.playersdk.JeffPlayer;
import com.jeffmony.playersdk.common.PlayerSettings;
import com.jeffmony.playersdk.common.PlayerType;
import com.jeffmony.playersdk.common.SeekType;
import com.jeffmony.playersdk.control.LocalProxyVideoControl;
import com.jeffmony.videocache.utils.LogUtils;
import com.jeffmony.videocache.utils.ProxyCacheUtils;
import com.jeffmony.videocache.utils.TimeUtils;

public class VideoTestPlayActivity extends Activity {

    private static final String TAG = "VideoPlayActivity";

    private final static int MSG_UPDATE_VIDEOSIZE = 1;
    private final static int MSG_UPDATE_VIDEOTIME = 2;

    private final static int MAX_PROGRESS = 1000;

    private String mVideoUrl;
    private Size mScreenSize;
    private int mVideoWidth;
    private int mVideoHeight;
    private SeekBar mProgressView;
    private TextView mTimeView;
    private ImageButton mVideoStatusBtn;
    private VideoStatus mVideoStatus;

    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_test_play);
        mScreenSize = ScreenUtils.getScreenSize(this.getApplicationContext());

        mVideoUrl = getIntent().getStringExtra("video_url");
//        mLocalProxyVideoControl = new LocalProxyVideoControl();

        setPlayer1();
//        setPlayer2();
    }

    private void setPlayer1(){
        PlayerView playerView = findViewById(R.id.video_textureview);
        ProxyCacheUtils.getConfig().setUseOkHttp(true);

        TrackSelector trackSelector  = new DefaultTrackSelector(this);
        LoadControl loadControl   = new DefaultLoadControl();

        SimpleExoPlayer simpleExoPlayer = ExoPlayerFactory.newSimpleInstance(this, trackSelector,loadControl);

        playerView.setPlayer(simpleExoPlayer);
        playerView.setControllerAutoShow(false);
        playerView.setControllerHideOnTouch(false);
        playerView.setUseController(false);
        playerView.setControllerAutoShow(false);
//        playerView.controllerShowTimeoutMs = 0;
//        playerView.controllerHideOnTouch = false;
//        playerView.useController = false;
//        playerView.controllerAutoShow = false;
        playerView.setBackgroundColor(this.getResources().getColor(R.color.transparent));
        playerView.setKeepContentOnPlayerReset(true);

        String origalUrl = "";
        origalUrl = "https://sf1-cdn-tos.huoshanstatic.com/obj/media-fe/xgplayer_doc_video/hls/xgplayer-demo.m3u8";
//        origalUrl = "https://test-streams.mux.dev/x36xhzz/x36xhzz.m3u8";
        String playerInfo = Util.getUserAgent(this, this.getResources().getString(R.string.app_name));
        DataSource.Factory dataSourceFactory = new DefaultDataSourceFactory(this, playerInfo);
        MediaSource mediaSource =new HlsMediaSource.Factory(dataSourceFactory).createMediaSource(Uri.parse(origalUrl));

        simpleExoPlayer.prepare(buildValidUrl(Uri.parse(origalUrl),origalUrl,this));
//        simpleExoPlayer.prepare(mediaSource);
//        simpleExoPlayer.prepare(new MediaSource());
        simpleExoPlayer.setPlayWhenReady(true) ;
        simpleExoPlayer.addListener(new Player.EventListener() {
            @Override
            public void onPlayerError(ExoPlaybackException error) {
                Player.EventListener.super.onPlayerError(error);
                Log.d(TAG,"onPlayerError" + error.toString());
            }
        });
    }

    private void setPlayer2(){
        PlayerView playerView = findViewById(R.id.video_textureview2);
        TrackSelector trackSelector  = new DefaultTrackSelector(this);
        LoadControl loadControl   = new DefaultLoadControl();
        SimpleExoPlayer simpleExoPlayer = ExoPlayerFactory.newSimpleInstance(this, trackSelector,loadControl);
        playerView.setPlayer(simpleExoPlayer);
        playerView.setControllerAutoShow(false);
        playerView.setControllerHideOnTouch(false);
        playerView.setUseController(false);
        playerView.setControllerAutoShow(false);
//        playerView.controllerShowTimeoutMs = 0;
//        playerView.controllerHideOnTouch = false;
//        playerView.useController = false;
//        playerView.controllerAutoShow = false;
        playerView.setBackgroundColor(this.getResources().getColor(R.color.transparent));
        playerView.setKeepContentOnPlayerReset(true);

        String origalUrl = "";
//        origalUrl = "https://sf1-cdn-tos.huoshanstatic.com/obj/media-fe/xgplayer_doc_video/hls/xgplayer-demo.m3u8";
        origalUrl = "http://devimages.apple.com/iphone/samples/bipbop/bipbopall.m3u8";
        String playerInfo = Util.getUserAgent(this, this.getResources().getString(R.string.app_name));
        DataSource.Factory dataSourceFactory = new DefaultDataSourceFactory(this, playerInfo);
        MediaSource mediaSource =new HlsMediaSource.Factory(dataSourceFactory).createMediaSource(Uri.parse(origalUrl));
        simpleExoPlayer.prepare(buildValidUrl2(Uri.parse(origalUrl),origalUrl,this));

//        simpleExoPlayer.prepare(mediaSource);
//        simpleExoPlayer.prepare(new MediaSource());
        simpleExoPlayer.setPlayWhenReady(true) ;
        simpleExoPlayer.addListener(new Player.EventListener() {
            @Override
            public void onPlayerError(ExoPlaybackException error) {
                Player.EventListener.super.onPlayerError(error);
                Log.d(TAG,"onPlayerError" + error.toString());
            }
        });
    }


    protected boolean mIsM3U8 = false;
//    protected LocalProxyVideoControl mLocalProxyVideoControl;

    private MediaSource buildValidUrl(Uri uri,String mVideoUrl,Context mContext){
        mIsM3U8 = com.jeffmony.videocache.utils.ProxyCacheUtils.isM3U8(uri.toString(), null);
        String playUrl = ProxyCacheUtils.getProxyUrl(uri.toString(), null, null);
        //请求放在客户端,非常便于控制
        LocalProxyVideoControl mLocalProxyVideoControl = new LocalProxyVideoControl();
        mLocalProxyVideoControl.startRequestVideoInfo(uri.toString(), null, null);
        String playerInfo = Util.getUserAgent(mContext, mContext.getResources().getString(R.string.app_name));
        DataSource.Factory dataSourceFactory = new DefaultDataSourceFactory(mContext, playerInfo);
        return new HlsMediaSource.Factory(dataSourceFactory).createMediaSource(Uri.parse(playUrl));
    }

    private MediaSource buildValidUrl2(Uri uri,String mVideoUrl,Context mContext){
        mIsM3U8 = com.jeffmony.videocache.utils.ProxyCacheUtils.isM3U8(uri.toString(), null);
        String playUrl = ProxyCacheUtils.getProxyUrl(uri.toString(), null, null);
        //请求放在客户端,非常便于控制
        LocalProxyVideoControl mLocalProxyVideoControl = new LocalProxyVideoControl();
        mLocalProxyVideoControl.startRequestVideoInfo(uri.toString(), null, null);
        String playerInfo = Util.getUserAgent(mContext, mContext.getResources().getString(R.string.app_name));
        DataSource.Factory dataSourceFactory = new DefaultDataSourceFactory(mContext, playerInfo);
        return new HlsMediaSource.Factory(dataSourceFactory).createMediaSource(Uri.parse(playUrl));
    }


    private DataSource.Factory buildDataSourceFactory(Context mContext) {
        String userAgent = Util.getUserAgent(mContext, "JeffPlayerSDK");
        DefaultDataSourceFactory upstreamFactory;
        upstreamFactory = new DefaultDataSourceFactory(mContext, new DefaultHttpDataSourceFactory(userAgent));
        return upstreamFactory;
    }
}
